package com.example.controller.weixiubaoyang;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.annotation.Log;
import com.example.common.result.PageResult;
import com.example.common.result.Result;
import com.example.entity.dto.weixiubaoyang.*;
import com.example.entity.mysql.Resource;
import com.example.entity.vo.pc.ListWorkResourceVO;
import com.example.entity.vo.pc.MoctyPlus;
import com.example.entity.vo.weixiubaoyang.ReceiptMouldListVo;
import com.example.entity.vo.weixiubaoyang.ReceiptMouldVo;
import com.example.entity.vo.weixiubaoyang.ReturnMouldDetailVo;
import com.example.entity.vo.weixiubaoyang.ReturnMouldListVo;
import com.example.entity.yifei.*;
import com.example.enums.MessageTypeEnum;
import com.example.enums.MouldStatusEnum;
import com.example.enums.ZnxStatusEnum;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.mapper.pc.ResourceMapper;
import com.example.mapper.pc.WorkresourceMapper;
import com.example.service.*;
import com.example.service.pc.ResourceService;
import com.example.service.weixiubaoyang.ReceiptService;
import com.example.untils.BeanUtils;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@RestController
@RequestMapping("/api/receipt")
@Api(tags = "领模单接口")
public class ReceiptController {
    @Autowired
    private ReceiptService receiptService;
    // 领用单单头
    @Autowired
    private EqttsMapper eqttsMapper;
    // 领用单单身
    @Autowired
    private EqtttService eqtttService;
    // 领用单单身
    @Autowired
    private EqtttMapper eqtttMapper;
    //模具/模仁状态
    @Autowired
    private ResourceService resourceService;
    // 归还单单头
    @Autowired
    private EqttuMapper eqttuMapper;
    // 归还单单身
    @Autowired
    private EqttvService eqttvService;
    @Autowired
    private EqttvMapper eqttvMapper;
    @Autowired
    private MoctyMapper moctyMapper;
    @Autowired
    private WorkresourceMapper workresourceMapper;
    @Autowired
    private CmsmdService cmsmdService;
    @Autowired
    private ZnxService znxService;
    @Autowired
    private SfctaMapper sfctaMapper;
    @Autowired
    private SFCTEMapper sfcteMapper;
    @Autowired
    private MoctaMapper moctaMapper;
    @Autowired
    private CmsmeMapper cmsmeMapper;
    @Autowired
    private SFCTDMapper sfctdMapper;
    @Autowired
    private InvmbMapper invmbMapper;
    @Autowired
    private QmsmgMapper qmsmgMapper;
    @Autowired
    private IHeadMapper iHeadMapper;
    @Autowired
    private CmsmvMapper cmsmvMapper;
    @Autowired
    private CmsmdMapper cmsmdMapper;
    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private ResourceusehisMapper resourceusehisMapper;
    @Autowired
    private MaintainplanMapper maintainplanMapper;
    @Autowired
    private MaintainplanruleMapper maintainplanruleMapper;
    @Autowired
    private ResourceMaintainplanMapper resourceMaintainplanMapper;
    @Autowired
    private MaintainplanitemMapper maintainplanitemMapper;
    @Autowired
    private EqtteService eqtteService;
    @Autowired
    private EqtteMapper eqtteMapper;
    @Autowired
    private EqttfService eqttfService;
    @Autowired
    private EqttfMapper eqttfMapper;
    @Autowired
    private MaconlineinfoMapper maconlineinfoMapper;
    @Autowired
    private EqtttDMapper eqtttDMapper;
    @Autowired
    private EqtttDService eqtttDService;

    @ApiOperation("生成领模单列表")
    @PostMapping("receiptMouldList")
    public Result<List<ReceiptMouldListVo>> receiptMouldList() {
        // 不要装配车间的
        List<MoctyPlus> moctyList = moctyMapper.selListNoST4();

        if(moctyList.size() == 0) {
            return Result.success();
        }

        List<String> udf05List = new ArrayList<>();
        Map<String, MoctyPlus> moctyPlusMap = new HashMap<>();
        for(MoctyPlus t : moctyList) {
            udf05List.add(t.getUdf05());
            moctyPlusMap.put(t.getTy001().trim() + t.getTy002().trim(), t);
        }

        Map<String, String> cmsmdMap = new HashMap<>();
        List<Cmsmd> cmsmdList = cmsmdService.list();
        for(Cmsmd t : cmsmdList) cmsmdMap.put(t.getMd001().trim(), t.getMd002().trim());

        List<ListWorkResourceVO> PPRList = workresourceMapper.listWorkResourceVO(udf05List);

        Map<String, ReceiptMouldListVo> map = new HashMap<>();
        for(ListWorkResourceVO t : PPRList) {
            if(StringUtils.isNotEmpty(t.getUsePosition())) t.setUsePositionName(cmsmdMap.get(t.getUsePosition().trim()));
            MoctyPlus moctyPlus = moctyPlusMap.get(t.getWorkSingle().trim() + t.getWorkNo().trim());
            ReceiptMouldListVo x = map.get(t.getDeviceId().trim());
            t.setProductId(moctyPlus.getProductId());
            t.setProductName(moctyPlus.getProductName());
            t.setGdChanLiang(new BigDecimal(moctyPlus.getTy004()));
            t.setJitaizhipaishijian(moctyPlus.getUdf10());
            if(x != null) continue;
            map.put(t.getDeviceId().trim(), new ReceiptMouldListVo(t.getResourceType(), t.getResourceId(), t.getDeviceId(), t.getDeviceName(), t.getStatus(), null));
        }

        for(ListWorkResourceVO t : PPRList) {
            //System.out.println("Key: " + key + ", Value: " + map.get(key));
            ReceiptMouldListVo mouldListVo = map.get(t.getDeviceId().trim());
            List<ListWorkResourceVO> list = mouldListVo.getResourceList();
            if(list == null) list = new ArrayList<>();
            list.add(t);
            mouldListVo.setResourceList(list);
            map.put(t.getDeviceId().trim(), mouldListVo);
        }

        List<ReceiptMouldListVo> res = new ArrayList<>();
        for (String key : map.keySet()) {
            res.add(map.get(key));
        }
        return Result.success(res);
    }

    /**
     * 生成领模单
     * @param dto
     * @return
     */
    @Log("生成领模单")
    @ApiOperation("生成领模单")
    @PostMapping("receiptMould")
    @DSTransactional
    public Result receiptMould(@RequestBody ReceiptMouldDto dto) {
        // 1.插入单据
        // 1.1插入单头
        Eqtts eqtts = new Eqtts();
        eqtts.setCREATE_DATE(TimeUtils.getNowTime());
        eqtts.setTS001("Mu");
        eqtts.setTS002(eqttsMapper.getNewTS002(eqtts.getTS001()));
        eqtts.setTS007(TimeUtils.HZStdTime());
        eqtts.setTS013("生产");
        eqtts.setTS014("N");

        Set<String> set = new HashSet<>();

        // 将数组中一样的模具，全部并起来
        Map<String, List<ReceiptMouldItemDto>> map = new HashMap<>();
        for(ReceiptMouldItemDto receiptMouldItemDto : dto.getItemList()) {
            List<ReceiptMouldItemDto> list = map.get(receiptMouldItemDto.getTT005().trim());
            if(list == null) list = new ArrayList<>();
            list.add(receiptMouldItemDto);
            map.put(receiptMouldItemDto.getTT005().trim(), list);
            Cmsmd cmsmd = cmsmdService.getOne(new LambdaQueryWrapper<Cmsmd>().eq(Cmsmd::getMd001, receiptMouldItemDto.getTT011()));
            if(!set.contains(cmsmd.getMd002().trim())) {
                set.add(cmsmd.getMd002().trim());
            }
        }
        List<Eqttt> eqtttList = new ArrayList<>();
        List<EqtttD> eqtttDList = new ArrayList<>();
        int idx = 1;
        for (Map.Entry<String, List<ReceiptMouldItemDto>> entry : map.entrySet()) {
            String key = entry.getKey();
            // 判断模具/模仁状态
            Resource mould = resourceService.getOne(new LambdaQueryWrapper<Resource>()
                    .eq(Resource::getDeviceid, key));

            if(!mould.getStatus().equals(MouldStatusEnum.XianZhi.getValue()) && !mould.getStatus().equals(MouldStatusEnum.YiShenHe.getValue())){
                throw new CustomException("500", "模具/模仁: " + mould.getDevicename() +" 不处于闲置状态，无法领取");
            }
            // 如果之前有一个未结束的领模单。已经领过这个了。那么就不能再生成新的了
            String lingmudan = eqtttMapper.selMacNoResult(mould.getDeviceid());
            if(lingmudan != null) {
                throw new CustomException("500", "模具/模仁: " + mould.getDevicename() +" 已存在未结束的领模单，无法领取");
            }
            Eqttt eqttt = new Eqttt();
            eqttt.setTT001(eqtts.getTS001());
            eqttt.setTT002(eqtts.getTS002());
            eqttt.setTT003(String.format("%03d", idx));  idx++;
            eqttt.setCREATE_DATE(TimeUtils.getNowTime());
            List<ReceiptMouldItemDto> receiptMouldItemDtoList = entry.getValue();  // 子单身
            BeanUtils.copyPropertiesIgnoreCase(receiptMouldItemDtoList.get(0), eqttt);
            eqttt.setTT021(null);
            eqttt.setTT022(null);
            eqttt.setUDF01(null);
            eqttt.setUDF02(null);
            eqttt.setUDF03(null);
            eqttt.setUDF04(null);

            eqtttList.add(eqttt);
            int sonIdx = 1;
            for(ReceiptMouldItemDto receiptMouldItemDto : receiptMouldItemDtoList) {  // 插入子单身
                EqtttD eqtttD = new EqtttD();
                eqtttD.setTtd001(eqtts.getTS001());
                eqtttD.setTtd002(eqtts.getTS002());
                eqtttD.setTtd003(eqttt.getTT003());
                eqtttD.setTtd004(String.format("%03d", sonIdx));
                sonIdx++;
                eqtttD.setTtd006(receiptMouldItemDto.getTT022().toString());  // 工单生产量
                eqtttD.setTtd007(receiptMouldItemDto.getUDF01());  // 派工单别
                eqtttD.setTtd008(receiptMouldItemDto.getUDF02());  // 派工单号
                eqtttD.setTtd009(receiptMouldItemDto.getUDF03());  // 产成品编号
                eqtttD.setTtd010(receiptMouldItemDto.getUDF04()); // 产成品名称
                // 预计生产模次数    工单生产量 / 模穴数
                if(eqttt.getUDF51() != null && eqttt.getUDF51().compareTo(new BigDecimal(0D)) > 0)
                    eqtttD.setTtd005(new BigDecimal(eqtttD.getTtd006()).divide(eqttt.getUDF51(), RoundingMode.CEILING).toString());
                eqtttDList.add(eqtttD);
            }


//            System.out.println(key + ": " + value);
        }

        //1.2插入单身  把相同模具的行并起来

//        idx = 1;
//        for(ReceiptMouldItemDto receiptMouldItemDto : dto.getItemList()) {
//            // 判断模具/模仁状态
//            Integer resourceId = Integer.parseInt(receiptMouldItemDto.getTT004());
//            Resource mould = resourceService.getOne(new LambdaQueryWrapper<Resource>()
//                    .eq(Resource::getResourceGroupIdIsF, resourceId));
//
//            if(!mould.getStatus().equals(MouldStatusEnum.XianZhi.getValue()) && !mould.getStatus().equals(MouldStatusEnum.YiShenHe.getValue())){
//                throw new CustomException("500", "模具/模仁: " + mould.getDevicename() +" 不处于闲置状态，无法领取");
//            }
//
//            // 如果之前有一个未结束的领模单。已经领过这个了。那么就不能再生成新的了
//            String lingmudan = eqtttMapper.selMacNoResult(mould.getDeviceid());
//            if(lingmudan != null) {
//                throw new CustomException("500", "模具/模仁: " + mould.getDevicename() +" 已存在未结束的领模单，无法领取");
//            }
//
//            Eqttt eqttt = new Eqttt();
//            eqttt.setTT001(eqtts.getTS001());
//            eqttt.setTT002(eqtts.getTS002());
//            eqttt.setTT003(String.format("%03d", idx));  idx++;
//            eqttt.setCREATE_DATE(TimeUtils.getNowTime());
//            BeanUtils.copyPropertiesIgnoreCase(receiptMouldItemDto, eqttt);
//
//            // 插入子单身
//
////            Mocty mocty = new Mocty();
////            mocty.setUdf09("Y");
////            moctyMapper.update(mocty, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, eqttt.getUDF01().trim() + eqttt.getUDF02().trim()));
//            // 预计生产模次数    工单生产量 / 模穴数
//            if(eqttt.getUDF51() != null && eqttt.getUDF51().compareTo(new BigDecimal(0D)) > 0) eqttt.setTT021(eqttt.getTT022().divide(eqttt.getUDF51(), RoundingMode.CEILING));
//
//            eqtttList.add(eqttt);
//
//            Cmsmd cmsmd = cmsmdService.getOne(new LambdaQueryWrapper<Cmsmd>().eq(Cmsmd::getMd001, eqttt.getTT011()));
//            if(!set.contains(cmsmd.getMd002().trim())) {
//                set.add(cmsmd.getMd002().trim());
//            }
//        }
        eqtttService.saveBatch(eqtttList);
        eqtttDService.saveBatch(eqtttDList);

        StringBuffer sb = new StringBuffer();
        for(String s : set) {
            sb.append(s).append(",");
        }
        if(sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
        eqtts.setTS012(sb.toString());  // 领用部门
        eqttsMapper.insert(eqtts);

        // 2.修改模具/模仁状态
//        List<Resource> mouldList = new ArrayList<>();
        for(ReceiptMouldItemDto receiptMouldItemDto : dto.getItemList()){
            Resource mould = new Resource();
//            mould.setResourceGroupIdIsF(Integer.parseInt(receiptMouldItemDto.getTT004()));
            mould.setStatus(MouldStatusEnum.DaiLingYong.getValue());
            resourceService.update(mould, new LambdaQueryWrapper<Resource>().eq(Resource::getResourceGroupIdIsF, Integer.parseInt(receiptMouldItemDto.getTT004())));
//            mouldList.add(mould);
        }
//        resourceService.updateBatchById(mouldList);

        // 消息通知
        znxService.saveZnxAndSendMessage(MessageTypeEnum.LINGMO.getValue(),
                "有一张领模单待处理, 单号：" + eqtts.getTS002(), ZnxStatusEnum.DAIBAN.getValue(), eqtts.getTS001()+":"+eqtts.getTS002());

        return Result.success();
    }

    @Log("保存领模单结果")
    @ApiOperation("保存领模单结果")
    @PostMapping("saveReceiptMouldResult")
    @DSTransactional
    public Result saveReceiptMouldResult(@RequestBody List<SaveReceiptMouldResultDto> list) {
        for(SaveReceiptMouldResultDto t : list) {
            Eqttt eqttt = new Eqttt();
            BeanUtils.copyPropertiesIgnoreCase(t, eqttt);
            Eqttt one = eqtttService.getOne(new LambdaQueryWrapper<Eqttt>().eq(Eqttt::getTT001, t.getTT001())
                    .eq(Eqttt::getTT002, t.getTT002()).eq(Eqttt::getTT003, t.getTT003()));
            if(StringUtils.isNotEmpty(one.getTT014())) {
                continue;
//                throw new CustomException("500", "领用结果不能修改");
            }
            eqtttService.update(eqttt, new LambdaQueryWrapper<Eqttt>().eq(Eqttt::getTT001, t.getTT001())
                    .eq(Eqttt::getTT002, t.getTT002()).eq(Eqttt::getTT003, t.getTT003()));
            if("OK".equals(t.getTT014().trim())) {
                Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, one.getTT005()));
                if(resource == null) {
                    throw new CustomException("500", "领用资源:" + one.getTT005() + "不存在!");
                }
                resource.setStatus(MouldStatusEnum.YiLingYong.getValue());
                resourceService.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, one.getTT005()));
            }else if("NG".equals(t.getTT014().trim())) {
                Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, one.getTT005()));
                if(resource == null) {
                    throw new CustomException("500", "领用资源:" + one.getTT005() + "不存在!");
                }
                resource.setStatus(MouldStatusEnum.XianZhi.getValue());
                resourceService.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, one.getTT005()));
            }
        }

        // 如果都有结果了，就把单头标记为 Y
        Integer count = eqtttMapper.selectCount(new LambdaQueryWrapper<Eqttt>().eq(Eqttt::getTT001, list.get(0).getTT001())
                .eq(Eqttt::getTT002, list.get(0).getTT002())
                .and(q -> q.isNull(Eqttt::getTT014)
                        .or().eq(Eqttt::getTT014, "")));
        if(count == null || count == 0) {
            Eqtts eqtts = new Eqtts();
            eqtts.setTS014("Y");
            eqttsMapper.update(eqtts, new LambdaQueryWrapper<Eqtts>().eq(Eqtts::getTS001, list.get(0).getTT001())
                    .eq(Eqtts::getTS002, list.get(0).getTT002()));
        }
        return Result.success();
    }

    /**
     * 分页获取单头信息
     * @param receiptMouldPageDto
     * @return
     */
    @ApiOperation("领模单，分页获取单头信息")
    @GetMapping("/page")
    public Result<PageResult<Eqtts>> page(ReceiptMouldPageDto receiptMouldPageDto){
        PageResult<Eqtts> pageResult = receiptService.pageQueryEqtts(receiptMouldPageDto);
        return Result.success(pageResult);
    }

    /**
     * 领模单详情
     * @param TS001
     * @param TS002
     * @return
     */
    @ApiOperation("领模单详情")
    @GetMapping ("/detail/{DanBie}/{DanHao}")
    public Result<ReceiptMouldVo> details(@PathVariable("DanBie") String TS001,
                            @PathVariable("DanHao") String TS002){
        ReceiptMouldVo receiptMouldVo = receiptService.details(TS001,TS002);
        return Result.success(receiptMouldVo);
    }

    @ApiOperation("生成退模单列表")
    @PostMapping("returnMouldList")
    public Result<List<ReturnMouldListVo>> returnMouldList() {
        //从资源表查询模仁/模具
        List<Resource> resourceList = resourceService.listMould();
        // 返回数据
        List<ReturnMouldListVo> returnMouldList = new ArrayList<>();
        for (Resource resource : resourceList) {
            //从领模单单身查询
            Eqttt eqttt = eqtttMapper.getLastest(resource.getDeviceid());
            if(eqttt == null){
               throw new CustomException("500","EQTTT为null");
            }
            ReturnMouldListVo vo = new ReturnMouldListVo();
            // 拷贝资源表到vo
            vo.setResourceId(String.valueOf(resource.getResourceGroupIdIsF()));
            vo.setResourceNo(resource.getDeviceid());
            vo.setResourceName(resource.getDevicename());
            vo.setResourceType(String.valueOf(resource.getResourceType()));
            vo.setRemark(resource.getRemark());
            vo.setCavityGuiGe(resource.getCavitySpecifications());
            if(resource.getCavityNumber() != null) vo.setCavityNum(BigDecimal.valueOf(resource.getCavityNumber()));
            //领模单身数据拷贝
            vo.setUsePosition(eqttt.getTT011());
            vo.setUseMachineID(eqttt.getUDF07());
            vo.setUseMachineNo(eqttt.getUDF08());
            vo.setUseMachineName(eqttt.getUDF09());

            vo.setReceiptMouldType(eqttt.getTT001());
            vo.setReceiptMouldNo(eqttt.getTT002());
            vo.setReceiptMouldSerialNo(eqttt.getTT003());
            returnMouldList.add(vo);
        }
        return Result.success(returnMouldList);
    }

    @Log("生成退模单")
    @ApiOperation("生成退模单")
    @PostMapping("returnMould")
    @DSTransactional
    public Result returnMould(@RequestBody ReturnMouldDto dto) {
        // 1.插入单据
        // 1.1插入单头
        Eqttu eqttu = new Eqttu();
        eqttu.setCREATE_DATE(TimeUtils.getNowTime());
        eqttu.setTU001("Mr");
        eqttu.setTU002(eqttuMapper.getNewTU002(eqttu.getTU001()));
        eqttu.setTU007(TimeUtils.HZStdTime());
        eqttu.setTU014("N");
        eqttuMapper.insert(eqttu);
        //1.2插入单身
        List<Eqttv> eqttvList = new ArrayList<>();
        List<String> bydList = new ArrayList<>();  // 要生成多少保养单
        int idx = 1;
        for(ReturnMouldItemDto returnMouldItemDto : dto.getItemList()) {
             //判断模具/模仁状态
//            Integer resourceId = Integer.parseInt(returnMouldItemDto.getTV004());
            Resource mould = resourceService.getOne(new LambdaQueryWrapper<Resource>()
                    .eq(Resource::getDeviceid, returnMouldItemDto.getTV005()));
            if(!mould.getStatus().equals(MouldStatusEnum.DaiGuiHuan.getValue())){
                throw new CustomException("500", "模具/模仁: " + mould.getDeviceid().trim() +" 不处于待归还状态.");
            }
            Eqttv eqttv = new Eqttv();
            eqttv.setTV001(eqttu.getTU001());
            eqttv.setTV002(eqttu.getTU002());
            eqttv.setTV003(String.format("%03d", idx));
            eqttv.setCREATE_DATE(TimeUtils.getNowTime());
            BeanUtils.copyPropertiesIgnoreCase(returnMouldItemDto, eqttv);
            eqttvList.add(eqttv);
            idx++;

            // 如果是模具的话, 往下生成保养单
            if(!"3".equals(returnMouldItemDto.getUDF01())) continue;

            // 生成保养单
            // 先查出来要触发哪几个
            List<Maintainplan> mpList = maintainplanMapper.mouldOnListTuiMoDan();
            for(Maintainplan plan : mpList) {
                // 生成保养单
                Eqtte eqtte = new Eqtte();
                eqtte.setTE001("BYD");
                eqtte.setTE002(eqtteMapper.selTe002(eqtte.getTE001()));
                eqtte.setTE003(TimeUtils.HZStdTime());
                eqtte.setTE004("1");
                eqtte.setTE008("3");
                eqtte.setTE010(returnMouldItemDto.getTV004());
                eqtte.setTE011(returnMouldItemDto.getTV005());
                eqtte.setTE012(returnMouldItemDto.getTV006());
                eqtte.setTE019("0");
                eqtte.setTE027("生成退模单: " + eqttu.getTU002() +"时自动生成。");
                eqtte.setTE028(plan.getMpuuid().toString());  // 计划UUID
                eqtte.setTE029(plan.getMpid());  // 计划编号
                eqtte.setTE030(plan.getMpname());  // 计划名称
                eqtte.setTE031(TimeUtils.HZStdTime());
                eqtte.setTE032(TimeUtils.HZStdTime());
                eqtte.setCREATE_DATE(TimeUtils.getFullNowTime());
                eqtte.setCREATOR("ERP");
                eqtteMapper.insert(eqtte);
                // 获取单身的项目 通过planitem
                List<Maintainplanitem> itemList = maintainplanitemMapper.selListByMpuuid(plan.getMpuuid());
                int sonIdx = 1;
                for(Maintainplanitem item : itemList) {
                    Eqttf eqttf = new Eqttf();
                    eqttf.setTF001(eqtte.getTE001());
                    eqttf.setTF002(eqtte.getTE002());
                    eqttf.setTF003(""+sonIdx);
                    eqttf.setUDF01(item.getMpiid());  // 维护编号
                    eqttf.setUDF02(item.getMpiname());  // 维护名称
                    eqttf.setTF005(item.getMpicontent());  // 维护内容
                    eqttf.setTF008(item.getMpiresulttype());  // 结果类型 1.文字 2.数值 3.日期[DEF:1]
                    eqttf.setCREATE_DATE(TimeUtils.getNowTime());
                    eqttf.setCREATOR("ERP");
                    eqttfMapper.insert(eqttf);
                    sonIdx++;
                }
                bydList.add(eqtte.getTE002());
            }

        }
        eqttvService.saveBatch(eqttvList);

        // 2.修改模具/模仁状态
        for(ReturnMouldItemDto returnMouldItemDto : dto.getItemList()) {
            Resource mould = new Resource();
            mould.setStatus(MouldStatusEnum.GuiHuanDaiQueRen.getValue());
            resourceService.update(mould, new LambdaQueryWrapper<Resource>()
                    .eq(Resource::getDeviceid, returnMouldItemDto.getTV005()));
        }
        // 消息通知
        znxService.saveZnxAndSendMessage(MessageTypeEnum.TUIMO.getValue(),
                "有一张退模单待处理, 单号：" + eqttu.getTU002(),
                ZnxStatusEnum.DAIBAN.getValue(), eqttu.getTU001()+":"+eqttu.getTU002());
        for(String s : bydList) {
            // 消息通知
            znxService.saveZnxAndSendMessage(MessageTypeEnum.BAOYANG.getValue(),
                    "有一张保养单待处理, 单号：" + s, ZnxStatusEnum.DAIBAN.getValue(), "BYD:"+s);
        }
        return Result.success();
    }

    @ApiOperation("归还退模单时可以选择的状态")
    @PostMapping("returnMouldStatusList")
    public Result<List<String>> saveReturnMouldResult() {
        List<String> res = new ArrayList<>();
        res.add(MouldStatusEnum.XianZhi.getValue());
        res.add(MouldStatusEnum.YiTingYong.getValue());
        res.add(MouldStatusEnum.YiZuoFei.getValue());
        return Result.success(res);
    }

    @Log("保存退模单状态")
    @ApiOperation("保存退模单状态")
    @PostMapping("saveReturnMouldResult")
    @DSTransactional
    public Result saveReturnMouldResult(@RequestBody List<SaveReturnMouldResultDto> dto) {

        for(SaveReturnMouldResultDto t : dto) {
            Eqttv eqttv = eqttvMapper.selectOne(new LambdaQueryWrapper<Eqttv>().eq(Eqttv::getTV001, t.getTV001()).eq(Eqttv::getTV002, t.getTV002()).eq(Eqttv::getTV003, t.getTV003()));
            if(eqttv == null) {
                throw new CustomException("500", "退模数据不存在!");
            }
            eqttv.setTV015(t.getTV015());
            if(StringUtils.isEmpty(eqttv.getTV014()) && StringUtils.isNotEmpty(t.getTV014())) { // 如果 归还后设备状态 是空的
                eqttv.setTV014(t.getTV014());
                // 找出resource修改状态
                Resource resource = new Resource();
                resource.setStatus(eqttv.getTV014());
                resourceService.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, eqttv.getTV005()));
            }
            eqttvMapper.update(eqttv, new LambdaQueryWrapper<Eqttv>().eq(Eqttv::getTV001, t.getTV001()).eq(Eqttv::getTV002, t.getTV002()).eq(Eqttv::getTV003, t.getTV003()));
        }

        // 如果都有结果了，就把单头标记为 Y
        Integer count = eqttvMapper.selectCount(new LambdaQueryWrapper<Eqttv>().eq(Eqttv::getTV001, dto.get(0).getTV001())
                .eq(Eqttv::getTV002, dto.get(0).getTV002())
                .and(q -> q.isNull(Eqttv::getTV014)
                        .or().eq(Eqttv::getTV014, "")));
        if(count == null || count == 0) {
            Eqttu eqttu = new Eqttu();
            eqttu.setTU014("Y");
            eqttuMapper.update(eqttu, new LambdaQueryWrapper<Eqttu>().eq(Eqttu::getTU001, dto.get(0).getTV001())
                    .eq(Eqttu::getTU002, dto.get(0).getTV002()));
        }
        return Result.success();
    }

    /**
     * 退模单头信息
     * @param returnMouldPageDto
     * @return
     */
    @ApiOperation("退模单头信息")
    @PostMapping("/returnPage")
    public Result<PageResult<Eqttu>> returnMouldPage(@RequestBody ReturnMouldPageDto returnMouldPageDto){
        PageResult<Eqttu> pageResult  = receiptService.pageQueryEqttu(returnMouldPageDto);
        return Result.success(pageResult);
    }

    @ApiOperation("退模单详情")
    @GetMapping("/returnMouldDetail/{danBie}/{danHao}")
    public Result<ReturnMouldDetailVo> returnMouldDetail(@PathVariable String danBie, @PathVariable String danHao){

        Eqttu eqttu = eqttuMapper.selectOne(new LambdaQueryWrapper<Eqttu>().eq(Eqttu::getTU001, danBie).eq(Eqttu::getTU002, danHao));
        if(eqttu == null) {
            return Result.error("退模单据不存在");
        }

        List<Eqttv> eqttvList = eqttvMapper.selectList(new LambdaQueryWrapper<Eqttv>().eq(Eqttv::getTV001, danBie).eq(Eqttv::getTV002, danHao));

        ReturnMouldDetailVo res = new ReturnMouldDetailVo();
        res.setEqttu(eqttu);
        res.setEqttvList(eqttvList);

        return Result.success(res);
    }

    @ApiOperation("找出在机器上空闲的模具/工装(退模单界面)")
    @PostMapping("/findIdleMouldList")
    public Result<List<ReturnMouldListVo>> findIdleMouldList(){
        // 1.先找出空闲的机器/生产线
        List<Resource> machineList = resourceMapper.findIdleMachine();
        if(machineList == null || machineList.size() == 0) return Result.success();
        // 2.去macOnlineInfo找出在里面的 空闲模具/工装
        List<ReturnMouldListVo> mouldList = maconlineinfoMapper.selListByMachineList(machineList);

        return Result.success(mouldList);
    }

}
